<template>
	<view style="height:100vh;background: #fff;">
		<view class="img-a">
			<view class="t-b">
				Individual Chat Room Tool
			</view>
		</view>
		<view class="login-view" style="">
			<view class="t-login">
				<form class="cl">
					<view class="t-a">
						<text class="txt">账号</text>
						<input type="text" name="phone" placeholder="请输入您的手机号" maxlength="20" v-model="phone" />
					</view>
					<view class="t-a">
						<text class="txt">密码</text>
						<input type="password" name="code" maxlength="18" placeholder="请输入您的密码" v-model="pwd" />
					</view>
					<button @tap="login()">登 录</button>
					<view class="reg" @tap="reg()">注 册</view>
				</form>
				<view class="t-f"><text>—————— 第三方账号登录 ——————</text></view>
				<view class="t-e cl">
					<view class="t-g" @tap="wxLogin()"><image src="https://zhoukaiwen.com/img/loginImg/wx.png"></image></view>
					<view class="t-g" @tap="zfbLogin()"><image src="https://zhoukaiwen.com/img/loginImg/qq.png"></image></view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import request from '@/common/request.js';
	export default {
		data() {
			return {
				phone: '', //手机号码
				pwd: '', //密码
				appInstance: undefined, //app实例
				loginStart: false, //标记login是否正在操作中
			};
		},
		onLoad() {
			this.appInstance = getApp();
		},
		onUnload() {
		},
		methods: {
			//当前登录按钮操作
			login() {
				var that = this;
				if(that.loginStart) {
					return;
				}
				that.loginStart = true;
				if (!that.phone) {
					uni.showToast({ title: '请输入您的手机号', icon: 'none' });
					that.loginStart = false;
					return;
				}
				// if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(that.phone)) {
				// 	uni.showToast({ title: '请输入正确手机号', icon: 'none' });
				// 	return;
				// }
				if (!that.pwd) {
					uni.showToast({ title: '请输入您的密码', icon: 'none' });
					that.loginStart = false;
					return;
				}
				
				// let token = 'Idi19Eh/XZdpgMRztWMi8MRqfpBrv5X25WOEfzRU17HMoI+wxyewdjVK2z5c56hr2b1TAUlX5VM='
				// // let token = 'dyN1BUbAMd6tncnRAQ2isOvvsEmtcSNRLI5ew4chutGItGiaz7sCGOd70Az9SawgZBZaYMMWH6g='
				// uni.setStorageSync('token', token)
				// uni.showToast({ title: '登录成功！', icon: 'none' });
				// this.gotCurrentUser();
				// //调用后端接口获取Msg_Server连接信息
				// this.msgServerChoose();
				// this.connectWebSocket(token);
				// uni.switchTab({
				// 	url: "/pages/index/index",
				// });
				
				let opts = {
					url: '/business2/user/login',
					method: 'post'
				};
				let params = {
					"username": that.phone,
					"password": that.pwd,
					"code": ""
				}
				request.httpRequest(opts,params).then(res => {
					uni.hideLoading();
					if (res.data.code == 200) {
						uni.setStorageSync('token', res.data.data);
						//调用后端接口获取Msg_Server连接信息
						that.msgServerChoose(res.data.data);
						uni.switchTab({
							url: "/pages/index/index",
						});
					} else {
						uni.showToast({
							title: '登录失败！',
							icon: 'none',
							duration: 1000
						});
					}
					that.loginStart = false;
				});
			},
			async msgServerChoose(token) {
				const _this = this
				let opts = {
					url: '/server/choose',
					method: 'get'
				}
				//标记是否获取到了MsgServer信息
				let msgServerConnectted = true;
				let wsUrl = '';
				const res = await request.httpTokenRequest(opts, {});
				if(!res.data.serverAddress) {
					uni.showToast({ title: '连接服务失败', icon: 'none' });
					msgServerConnectted = false;
				} else {
					wsUrl = 'ws://'+ res.data.serverAddress + ':' + res.data.serverPort + '/websocket'
					this.appInstance.globalData.wsBaseUrl = wsUrl
				}
				//执行后续操作(获取当前登录用户信息，连接WS服务端)
				_this.gotCurrentUser(token, wsUrl, msgServerConnectted)
			},
			async gotCurrentUser(token, wsUrl, msgServerConnectted) {
				const _this = this
				let opts = {
					url: '/business2/user/current/info',
					method: 'get'
				}
				//获取当前登录用户的信息
				const reps = await request.httpTokenRequest(opts, {});
				if (reps.data.code == 200) {
					uni.setStorageSync('currentUser', reps.data.data)
					//连接WS服务端
					if(msgServerConnectted) {
						_this.connectWebSocket(token, wsUrl, reps.data.data);
					}
				} else {
					console.error("获取当前登录用户信息失败!")
				}
			},
			//注册按钮点击
			reg() {
				uni.showToast({ title: '注册跳转', icon: 'none' });
			},
			//等三方微信登录
			wxLogin() {
				uni.showToast({ title: '微信登录', icon: 'none' });
			},
			//第三方支付宝登录
			zfbLogin() {
				uni.showToast({ title: '支付宝登录', icon: 'none' });
			},
			connectWebSocket(token, wsUrl, currUser) {
				this.appInstance.globalData.webSocket = uni.connectSocket({
					url: wsUrl,
					// url: 'ws://192.168.11.85:18183/websocket',
					complete: (e)=> {
						// uni.showToast({ title: '连接ws成功', icon: 'none' });
					}
				});
				
				this.appInstance.globalData.webSocket.onOpen(() => {
					this.appInstance.globalData.wsOpenStatus = true;
					uni.showToast({ title: 'WebSocket连接已打开!', icon: 'none' });
					this.sendToken(token, this.appInstance.globalData.webSocket, true, currUser.uid);
				});

				this.appInstance.globalData.webSocket.onMessage((message) => {
					console.log('收到来自WS服务器消息：' + message.data);
					let reps = JSON.parse(message.data)
					//只有token校验才可能出现非200的code
					if(reps.code != 200) {
						uni.showToast({ title: 'Token校验失败, 登录未通过!', icon: 'none' });
						return;
					}
					//表示token校验已通过
					if (reps.msg == 'token') {
						//通知后台上线成功
						this.noticeOnlineSuccess();
					} else if (reps.msg == 'history msgs') {
						//收到的历史消息,发送消息
						console.log("离线消息....")
						uni.$emit('historyMsgs', reps.data);
					} else if (reps.msg == 'online msgs') {
						//收到的历史消息,发送消息
						console.log("在线消息....")
						//向正在被打开的聊天室页面发送对应的在线消息
						const openningChatToUid = parseInt(uni.getStorageSync('currentChat'), 10)
						if(openningChatToUid && !isNaN(openningChatToUid)) {
							let onlineMsgs = [];
							reps.data.forEach(msg => {
								//仅将该toUid发送的消息发送到聊天室页面
								if(msg.msg.userinfo.uid == openningChatToUid) {
									uni.$emit('oneOnlineMsg', msg);
								} else {
									//将其他用户发送的消息发送到好友列表页面
									onlineMsgs.push(msg)
								}
							})
							if(onlineMsgs.length>0) {
								//向好友列表页发送在线消息
								uni.$emit('onlineMsgs', onlineMsgs);
							}
						} else {
							//向好友列表页发送在线消息
							uni.$emit('onlineMsgs', reps.data);
						}
						
					}
					
					
					
					
					
					
				});

				this.appInstance.globalData.webSocket.onError(() => {
					// console.log('WebSocket 出现异常错误: ' + error.errMsg);
					this.appInstance.globalData.wsOpenStatus = false;
					// uni.showToast({ title: 'WebSocket 出现异常错误!', icon: 'none' });
				});
				
				this.appInstance.globalData.webSocket.onClose(() => {
					console.log('WebSocket连接被客户端关闭.');
					this.appInstance.globalData.wsOpenStatus = false;
				});
			},
			sendToken(token, webSock, open, uid) {
				if(!open) {
					uni.showToast({ title: 'ws连接已关闭，无法发送token', icon: 'none' });
					return
				}
				
				const param = {
					"msgId": null,
					"messageType": "TOKEN",
					"fromUserId": uid,
					"toUserIds": null,
					"token": token,
					"msgContent": null,
					"time": 1
				}
				// uni.showToast({ title: '开始执行ws.sendToken: ' + uid, icon: 'none' });
				webSock.send({
					data: JSON.stringify(param),
					success: () => {
						console.log("前端发送Token信息到WS服务端成功.")
						// uni.showToast({ title: '前端发送Token信息到WS服务端成功: ' + uid, icon: 'none' });
					},
					fail: () => {
						uni.showToast({ title: '前端发送Token信息到WS服务端失败: ' + uid, icon: 'none' });
					}
					
				});
			},
			noticeOnlineSuccess() {
				let opts = {
					url: '/business1/talk/login/notice',
					method: 'post'
				}
				request.httpTokenRequest(opts, {}).then(reps => {
					if (reps.data.code == 200) {
						console.log("用户上线通知成功")
						//跳转到联系人页面
						uni.switchTab({
							url: "/pages/index/index",
						});
					} else {
						console.log("用户上线通知成功")
					}
				})
			
			},
			
			
		}
	};
</script>
<style>
	.txt {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}
	.img-a {
		width: 100%;
		height: 450rpx;
		background-image: url(https://zhoukaiwen.com/img/loginImg/head.png);
		background-size: 100%;
	}
	.reg {
		font-size: 28rpx;
		color: #fff;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 50rpx;
		font-weight: bold;
		background: #f5f6fa;
		color: #000000;
		text-align: center;
		margin-top: 30rpx;
	}

	.login-view {
		width: 100%;
		position: relative;
		margin-top: -120rpx;
		background-color: #ffffff;
		border-radius: 8% 8% 0% 0;
	}

	.t-login {
		width: 600rpx;
		margin: 0 auto;
		font-size: 28rpx;
		padding-top: 80rpx;
	}

	.t-login button {
		font-size: 28rpx;
		background: #2796f2;
		color: #fff;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 50rpx;
		font-weight: bold;
	}

	.t-login input {
		height: 90rpx;
		line-height: 90rpx;
		margin-bottom: 50rpx;
		border-bottom: 1px solid #e9e9e9;
		font-size: 28rpx;
	}

	.t-login .t-a {
		position: relative;
	}

	.t-b {
		text-align: center;
		font-size: 46rpx;
		color: #ffffff;
		padding: 130rpx 0 0 0;
		font-weight: bold;
		line-height: 70rpx;
	}

	.t-login .t-c {
		position: absolute;
		right: 22rpx;
		top: 22rpx;
		background: #5677fc;
		color: #fff;
		font-size: 24rpx;
		border-radius: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0 25rpx;
	}

	.t-login .t-d {
		text-align: center;
		color: #999;
		margin: 80rpx 0;
	}

	.t-login .t-e {
		text-align: center;
		width: 250rpx;
		margin: 80rpx auto 0;
	}

	.t-login .t-g {
		float: left;
		width: 50%;
	}

	.t-login .t-e image {
		width: 50rpx;
		height: 50rpx;
	}

	.t-login .t-f {
		text-align: center;
		margin: 150rpx 0 0 0;
		color: #666;
	}

	.t-login .t-f text {
		margin-left: 20rpx;
		color: #aaaaaa;
		font-size: 27rpx;
	}

	.t-login .uni-input-placeholder {
		color: #aeaeae;
	}

	.cl {
		zoom: 1;
	}

	.cl:after {
		clear: both;
		display: block;
		visibility: hidden;
		height: 0;
		content: '\20';
	}
</style>